package com.woniuxy.rbac.web.api;

import com.github.pagehelper.PageInfo;
import com.woniuxy.rbac.entity.ResponseResult;
import com.woniuxy.rbac.entity.Role;
import com.woniuxy.rbac.exception.RoleNameExistException;
import com.woniuxy.rbac.service.RoleService;
import com.woniuxy.rbac.vo.RoleVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * @Auther: L
 */
@Slf4j
@RestController
@RequestMapping("/role")
public class RoleController {
    @Autowired
    private RoleService roleService;

    @GetMapping("/getall")
    public ResponseResult<List<Role>> getAll() {
        return new ResponseResult<>(roleService.getAll());
    }

    @PostMapping("/add")
    public ResponseResult<Void> add(@RequestBody @Valid RoleVO roleVO) {
        log.debug("角色名:{},角色描述:{}", roleVO.getRole().getName(), roleVO.getRole().getDescription());
        roleService.add(roleVO.getRole(), roleVO.getPermIds());
        return ResponseResult.SUCCESS;
    }

    @PostMapping("/update")
    public ResponseResult<Void> update(@RequestBody @Validated RoleVO roleVO) {
        log.debug("角色ID:{}，角色名:{},角色描述:{}", roleVO.getRole().getId(), roleVO.getRole().getName(), roleVO.getRole().getDescription());
        roleService.update(roleVO.getRole(), roleVO.getPermIds());
        return ResponseResult.SUCCESS;
    }

    @ExceptionHandler(RoleNameExistException.class)
    public ResponseResult<Void> handleException() {
        return new ResponseResult<>(501, "角色重复");
    }


    @GetMapping("view/{id}")
    public ResponseResult<Role> getById(@PathVariable int id) {
        return new ResponseResult<>(roleService.getById(id));
    }

    @GetMapping({"page/{pageNum}", "page"})
    public ResponseResult<PageInfo<Role>> getByPage(@PathVariable(required = false) Integer pageNum) {
        return new ResponseResult<>(roleService.getByCondition(pageNum == null ? 1 : pageNum, null));
    }
}
